import { createRouter, createWebHistory } from "vue-router";
import ShowDB from "@/components/ShowDB";
import GenerateKey from "@/components/GenerateKey";
import ExtendKey from "@/components/ExtendKey";
import Home from "@/components/Home";
import Auth from "@/components/Auth";
import { ElMessage, ElNotification } from "element-plus";
import axios from "axios";

const routerHistory = createWebHistory();
const routes = [
  { path: "/", redirect: "/auth" },
  {
    path: "/auth",
    component: Auth,
    name: "auth",
  },
  {
    path: "/home",
    component: Home,
    name: "home",
    redirect: "/home/generate_key",
    meta: {
      leaf: true,
      requireAuth: true,
    },
    children: [
      {
        path: "/home/show_db",
        component: ShowDB,
        name: "show_db",
        meta: {
          title: "查看密钥",
          requireAuth: true,
        },
      },
      {
        path: "/home/generate_key",
        name: "generate_key",
        component: GenerateKey,
        meta: {
          title: "生成密钥",
          hidden: false,
          requireAuth: true,
          leaf: false,
        },
      },
      {
        path: "/home/extend_key",
        name: "extend_key",
        component: ExtendKey,
        meta: {
          title: "续费",
          hidden: false,
          requireAuth: true,
          leaf: false,
        },
      },
    ],
  },
];

const router = createRouter({
  history: routerHistory,
  routes,
});
console.log(routes);

router.beforeEach((to, from, next) => {
  if(to.path == "/auth"){
    if (
      localStorage.getItem("auth_key") != null &&
      localStorage.getItem("auth_key") != undefined
    ) {
      next("/home")
      return
    }
  }
  if (to.meta.requireAuth) {
    console.log("auth" + localStorage.getItem("auth_key"));
    if (
      localStorage.getItem("auth_key") == null ||
      localStorage.getItem("auth_key") == undefined
    ) {
      ElMessage.error("请先验证身份！！");
      next("/auth");
    } else {
      axios.get("/api/login",{
        params: {
          auth: localStorage.getItem("auth_key")
        }
      }).then(res => {
        console.log(res.data.data)
      })
      .catch(err => {
        ElNotification({
          title: '错误',
          type: 'error',
          message: '身份验证已过期！！'
        });
        console.error(err)
      })
      next();
    }
  } else {
    next();
  }
});

export default router;
